const {
    query
} = require("../../db/index");
const {
    json,
    isEmpty,
} = require("../../utils/index");
const {
    insertLogInfo
} = require("../../utils/log-tools");
const utils = require("../../utils/index");
// 引入配置文件
const config = require("../../config");
const os = require("os");
// 引入token生成模块
const jwt = require("jsonwebtoken");
const bcryptjs = require("bcryptjs");
const path = require("path");

// 定义一些常量
const THEME_CONFIG_PATH = path.join(process.cwd(),"configs","theme.json");
const SERVER_INFO_PATH = path.join(process.cwd(),"configs","server_info.json");

//1. 管理员登录接口
exports.login = (req, res) => {
    const {
        admin_name,
        admin_pwd
    } = req.body;
    // userinfo.admin_pwd = bcryptjs.hashSync(userinfo.admin_pwd,10); //明文密码，随机盐长度
    const sqlStr = "select * from t_admin where admin_name=?";
    query(sqlStr, admin_name).then(result => {
        if (result.length > 0) {
            //查找到了用户名,并对比密码
            if (bcryptjs.compareSync(admin_pwd, result[0].admin_pwd)) {
                // 生成token
                const tokenStr = jwt.sign({
                    ...result[0]
                }, config.jwtSecretKey, {
                    expiresIn: config.expiresIn
                });
                return res.send(json("登录成功", 0, {
                    id: result[0].id,
                    token: "Bearer " + tokenStr
                }));
            }
            return res.send(json("密码错误"));
        }
        //未查找到用户名
        res.send(json("账号不存在"));
    }).catch(err => {
        insertLogInfo(0, err);
        res.send(json("服务器异常"));
    })
}


//2. 获取管理员列表
exports.adminList = (req, res) => {
    let {
        pageNum,
        pageSize
    } = req.body;
    const sqlStr = "select * from t_admin limit ?,?";
    query(sqlStr, [--pageNum * pageSize, pageSize])
        .then(result => {
            res.send(json("success", 0, result));
        }).catch(err => {
            insertLogInfo(0, err);
            res.send(json("服务器异常"));
        });
}


//3. 修改管理员信息
exports.updateInfo = (req, res) => {
    let {
        id,
        admin_pwd
    } = req.body;
    const sqlStr = "update t_admin set ? where id=?";
    // 把密码进行加密
    if (!isEmpty(admin_pwd)) {
        req.body.admin_pwd = bcryptjs.hashSync(admin_pwd, 10);
    }
    query(sqlStr, [req.body, id])
        .then(result => {
            // 执行sql成功 但未成功影响行数
            if (result.affectedRows !== 1) {
                return res.send(json("修改失败"));
            }
            res.send(json("修改成功", 0));
        }).catch(err => {
            insertLogInfo(0, err);
            res.send(json("服务器异常"));
        })
}


// 6. 修改主题配置信息
exports.update_theme_config = (req, res) => {
    const {
        key,
        val
    } = req.body;
    utils.readFile(THEME_CONFIG_PATH).then(data => {
        let json_data = JSON.parse(data.toString());
        if (isEmpty(json_data[key])) {
            return res.send(json("该属性不存在"));
        }
        json_data[key] = val;
        return utils.writeFile(THEME_CONFIG_PATH, JSON.stringify(json_data));
    }).then(() => {
        res.send(json("修改成功", 0));
    }).catch(err => {
        insertLogInfo(0, err);
        return res.send(json("服务器异常"));
    })
}


// 7. 获取服务器信息
exports.server_info = (req, res) => {
    const data = {
        totalmem: os.totalmem(), // 内存总量
        freemem: os.freemem(), // 内存使用量
        platform: os.type(), // 平台操作系统
        uptime: os.uptime(), // 系统运行时间
        create_time: Date.now(), // 请求时间
        webRunTime: config.webRunTime // 网站运行时间
    };
    res.send(json("success", 0, data));
}


// 8. 获取访问量
exports.request = function (req, res) {
    let startTime = 0 // 开始时间戳
    let endTime = 0 // 结束时间戳
    let startDate = new Date()
    let endDate = new Date(startDate.getTime())
    
    // 克隆个时间节点,记录请求的这一天，防止后面因为运行时间过长刚好跳过当天然后出现不精准等bug
    const todayDate = new Date(startDate.getTime())
    let dayObj = {
        "week": 6, // 按1周
        "month": 29, // 按1月
        "year": 364 // 按1年
    }
    const _type = req.query.type
    if (isEmpty(dayObj[_type])) {
        return res.send(json("参数错误"))
    }
    const sqlStr = "select ip,create_time from t_request_log where create_time<? and create_time>=?"
    const querySql = () => {
        return new Promise((resolve) => {
            query(sqlStr, [endTime, startTime]).then(result => {
                resolve(result)
            }).catch(err => {
                insertLogInfo(0, err)
                res.send(json("服务器异常"))
            })
        })
    }
    // 先算出明天0点
    endDate.setDate(endDate.getDate() + 1)
    endDate.setHours(0, 0, 0, 0)
    endTime = endDate.getTime()
    startDate.setDate(startDate.getDate() - dayObj[_type])
    startDate.setHours(0, 0, 0, 0)
    startTime = startDate.getTime()

    querySql().then(result => {
        let head = new Date(todayDate.getTime())
        let tail = new Date(head.getTime())
        let hs = 0
        let ts = 0
        let length = _type === "year" ? 12 : dayObj[_type] + 1
        let returnJson = {
            start_time: 0, // 返回，数据开始的那天
            end_time: 0, // 返回，数据结束的那天
            days: _type === "year" ? new Array(12).fill(0) : new Array(dayObj[_type]+1).fill(0), // 返回，对应的请求数
            all_request: 0, // 全部请求数量
            today_request_count: 0 // 今天请求数量
        }
        let monthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
        
        // 获取按1周或1月或1年的请求数据
            
        for (let i = 0; i < length; i++) {
            if (_type === "year") {
                tail.setDate(monthDays[tail.getMonth()])
                head.setDate(1)
            }
            tail.setHours(23, 59, 59, 59)
            head.setHours(0, 0, 0, 0)
            hs = tail.getTime()
            ts = head.getTime()
            let newList = [] // 用来保存新的result，用内存换效率了，尽量减少循环次数
            let ips_obj = {} // 存当天的IP合集
            for (let j = 0; j < result.length; j++) {
                if (result[j].create_time >= ts && result[j].create_time <= hs) {
                    if(!ips_obj[result[j].ip]){
                        returnJson.days[i]++;
                        ips_obj[result[j].ip] = 1;
                    }
                } else {
                    newList.push(result[j])
                }
            }
            result = newList
            // tail和head天数往后挪
            if (_type === "year") {
                // 考虑到前年的情况
                if (head.getMonth() === 0) {
                    head.setFullYear(head.getFullYear() - 1, 11, 31)
                } else {
                    head.setMonth(head.getMonth() - 1)
                }
            } else {
                head.setDate(head.getDate() - 1)
            }
            tail.setTime(head.getTime())
        }
        // 记录当天的请求量
        returnJson.today_request_count = returnJson.days[0];
        returnJson.all_request += returnJson.days.reduce((a,b)=>a+b);
        returnJson.start_time = head.getTime()
        returnJson.end_time = todayDate.getTime()
        res.send(json("success", 0, returnJson))
    })

}


// 9. 获取全部请求数据
exports.all_request = (req, res) => {
    const sqlStr = "select create_time from t_request_log"
    query(sqlStr).then(result => {
        res.send(json("success", 0, result))
    }).catch(err => {
        insertLogInfo(0, err)
        res.send(json("服务器异常"))
    })
}


// 修改公告内容
exports.update_notice = (req,res)=>{
    const notice = req.body.notice_content
    const dataJson = require("../../configs/server_info.json")
    dataJson.announcement = notice
    utils.writeFile(SERVER_INFO_PATH, JSON.stringify(dataJson)).then(result=>{
        res.send(json("success",0))
    }).catch(err=>{
        insertLogInfo(0, err)
        res.send(json("服务器异常"))
    })
}